package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0.0
 * @program:sky-take-out
 * @author: CaoYuWei
 * @create:2023-02-15 09:59:51
 **/
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 用户下单  分为三部分：order、orderDetail、addressBook
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO userSubmit(OrdersSubmitDTO ordersSubmitDTO) {
        //1、地址铺为空、购物车数据为空 抛出异常
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());//获取地址
        if(addressBook == null){
            throw  new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);//地址为空不能下单
        }

        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());//当前用户的购物车

        //2、向订单表插入1条数据
        Orders orders = new Orders();//订单
        BeanUtils.copyProperties(ordersSubmitDTO,orders);//将dto数据拷贝至orders
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//订单号（需要转换类型）
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(Orders.PENDING_PAYMENT);//待支付
        orders.setPayStatus(Orders.UN_PAID);//刚刚下单 还未支付
        orders.setOrderTime(LocalDateTime.now());
        orderMapper.insert(orders);//封装完成之后  进行插入操作（order表）

        //3、向订单明细表中添加n条数据
        List<OrderDetail> orderDetails = new ArrayList<>();//多条订单详情数据（与订单关联的）
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if(shoppingCartList == null || shoppingCartList.size() >0){
            throw  new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);//购物车为空不能下单
        }
        for (ShoppingCart cart : shoppingCartList) {//订单明细
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());//需要返回主键值（1:n）
            orderDetails.add(orderDetail);
        }

        orderDetailMapper.insertBatch(orderDetails);//订单菜品或套餐批量插入
        shoppingCartMapper.deleteOneCart(BaseContext.getCurrentId());//4、清空购物车

        //构造vo对象 并返回
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder() //封装返回
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;
    }



    /**
     * 查看历史订单
     * @return
     */
    @Override
    public PageResult selectHistoryOrders(int page, int pageSize, Integer status) {
        PageHelper.startPage(page,pageSize); //分页查询
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        Page<Orders> ordersPage = orderMapper.selectHistoryOrders(ordersPageQueryDTO); //订单分页查询
        List<OrderVO> orderVOList = new ArrayList<>(); //展示前端的数据

        for (Orders orders : ordersPage) {
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orders.getId()); //订单菜品套餐详情
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            orderVO.setOrderDetailList(orderDetails); //数据封装至vo
            orderVOList.add(orderVO); //voList封装到orderVOList
        }

        return new PageResult(ordersPage.getTotal(),orderVOList);
    }

    /**
     * 查看历史订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO selectOrderDetails(Long id) {
        Orders orders = orderMapper.getById(id); //获取菜品id
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(orders.getId()); //拿到list 封装至vo
        orderVO.setOrderDetailList(byOrderId);
        return orderVO;
    }


    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        Orders orderId = orderMapper.getById(id);
        Orders orders = new Orders();
        orders.setId(orderId.getId());
        orders.setStatus(Orders.CANCELLED);//取消状态
        orders.setCancelTime(LocalDateTime.now());//设置关闭时间
        orderMapper.update(orders);
    }

    /**
     * 再来一单（订单详情---->购物车）
     * @param id
     */
    @Override
    public void repetitionOrder(Long id) {
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);//根据id查询订单的详情（菜品和套餐）
        List<ShoppingCart> cartList = new ArrayList<>(); //创建购物车的list

        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            cartList.add(shoppingCart);//一个一个加入购物车
        }
        shoppingCartMapper.insertBatch(cartList);
    }


    /**
     * 客户端订单查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult orderSelect(OrdersPageQueryDTO ordersPageQueryDTO) {
        //这段代码 写了统计接口之后 显示不出详情
      /*  PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());//分页查询
        Page<Orders> page = orderMapper.orderSelect(ordersPageQueryDTO);
        List<Orders> ordersList = page.getResult();

        //返回订单详细地址
        for (Orders orders : ordersList) {
            AddressBook ressBook = orderMapper.getRessBook(orders.getAddressBookId());
            String  address = ressBook.getProvinceName() +ressBook.getCityName()+ ressBook.getDistrictName() +ressBook.getDetail();
            orders.setAddress(address);
        }
        return new PageResult(page.getTotal(),ordersList);*/
        //分页查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.orderSelect(ordersPageQueryDTO);

        //订单菜品信息查询
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();

        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {

                //获取到具体地址
                AddressBook addressBook = orderMapper.getAddressBook(orders.getAddressBookId());
                String address = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
                orders.setAddress(address);

                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);

                //获取到菜品名和数量
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }

        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            String orderDish = orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
            orderDishList.add(orderDish);
        }
        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }


    /**
     * 不同状态数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        Orders orders = new Orders();
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        Integer toBeConfirmed = orderMapper.statisticsStatus(orders);
        orders.setStatus(Orders.CONFIRMED);
        Integer confirmed = orderMapper.statisticsStatus(orders);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        Integer deliveryInProgress = orderMapper.statisticsStatus(orders);


        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);//状态为3
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);//派送订单
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = new Orders();
        orderMapper.getById(id);
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);//已完
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders  orders = new Orders();
        Orders orderById = orderMapper.getById(ordersRejectionDTO.getId());//根据id查询订单

        if(!orderById.getStatus().equals(Orders.TO_BE_CONFIRMED)){//如果订单为 待接单 才可以拒单
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR); //订单状态错误
        }
        orders.setId(orderById.getId());
        orders.setStatus(Orders.CANCELLED);//取消
        orders.setRejectionReason(ordersRejectionDTO.getIonReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        Orders orderById = orderMapper.getById(ordersCancelDTO.getId());
        orders.setId(orderById.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }
}